<template>
  <div class="follow-page" :class="{ 'slide-in': isVisible }">
    <div class="header">
      <van-icon name="arrow-left" class="back-icon" @click="handleBack" />
      <span class="title">我的关注</span>
    </div>

    <div class="content">
      <div v-if="followedAuthors.length === 0" class="empty-state">
        <van-empty description="暂无关注的作者" />
      </div>

      <div v-else class="follow-list">
        <div v-for="author in followedAuthors" :key="String(author.id)" class="follow-item">
          <div class="avatar-wrapper">
            <img :src="author.icon || ''" class="avatar" alt="" />
          </div>
          <div class="author-info">
            <div class="author-name">{{ author.name }}</div>
            <div class="author-description">{{ author.description || '暂无描述' }}</div>
          </div>
          <div class="follow-btn" :class="{ 'unfollowed': isFollowedMap[String(author.id)] === false }"
            @click="handleToggleFollow(author)">
            {{ isFollowedMap[String(author.id)] !== false ? '已关注' : '关注' }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onActivated, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useFollowsStore, type FollowedAuthor } from '@/stores/follows'

const router = useRouter()
const followsStore = useFollowsStore()

// 动画状态
const isVisible = ref(false)

// 跟踪每个作者的关注状态（用于取消关注时的临时状态）
const isFollowedMap = ref<Record<string, boolean>>({})

// 关注的作者列表
const followedAuthors = computed(() => {
  return followsStore.followedAuthors
})

// 初始化关注状态映射
const initFollowedMap = () => {
  const map: Record<string, boolean> = {}
  followsStore.followedAuthors.forEach((author) => {
    map[String(author.id)] = true
  })
  isFollowedMap.value = map
}

// 处理返回
const handleBack = () => {
  // 检查是否有取消关注的状态，如果有则从数组中删除
  const toRemove: string[] = []
  Object.keys(isFollowedMap.value).forEach((id) => {
    if (!isFollowedMap.value[id]) {
      toRemove.push(id)
    }
  })

  // 删除取消关注的作者
  toRemove.forEach((id) => {
    followsStore.removeFollow(id)
  })

  // 触发退出动画
  isVisible.value = false
  // 等待动画完成后再路由返回
  setTimeout(() => {
    router.back()
  }, 300)
}

// 处理切换关注状态
const handleToggleFollow = (author: FollowedAuthor) => {
  const authorId = String(author.id)
  const currentState = isFollowedMap.value[authorId]

  if (currentState !== false) {
    // 取消关注：只更新临时状态，不立即删除
    isFollowedMap.value[authorId] = false
  } else {
    // 重新关注：恢复状态
    isFollowedMap.value[authorId] = true
    // 如果不在列表中，重新添加
    if (!followsStore.isFollowed(author.id)) {
      followsStore.addFollow(author)
    }
  }
}

// 触发进入动画
const triggerEnterAnimation = () => {
  // 确保初始状态是隐藏的（translateX(100%)）
  isVisible.value = false

  // 延迟一帧确保DOM已渲染，然后触发进入动画
  requestAnimationFrame(() => {
    requestAnimationFrame(() => {
      isVisible.value = true
    })
  })
}

// 组件挂载时初始化
onMounted(() => {
  followsStore.loadFollows()
  initFollowedMap()
  triggerEnterAnimation()
})

// 组件激活时触发动画（处理 keep-alive 情况）
onActivated(() => {
  followsStore.loadFollows()
  initFollowedMap()
  triggerEnterAnimation()
})

// 组件卸载前保存状态
onBeforeUnmount(() => {
  isVisible.value = false
  // 删除取消关注的作者
  const toRemove: string[] = []
  Object.keys(isFollowedMap.value).forEach((id) => {
    if (!isFollowedMap.value[id]) {
      toRemove.push(id)
    }
  })

  toRemove.forEach((id) => {
    followsStore.removeFollow(id)
  })
})
</script>

<style scoped lang="less">
.follow-page {
  width: 100vw;
  min-height: 100vh;
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  transform: translateX(100%);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &.slide-in {
    transform: translateX(0);
  }
}

.header {
  width: 100%;
  height: 6vh;
  padding: 0 4vw;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 3vw;
  border-bottom: 1px solid #f5f5f5;
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 10;

  .back-icon {
    font-size: 18px;
    color: #333;
    cursor: pointer;
  }

  .title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }
}

.content {
  width: 100%;
  padding: 2vh 4vw;
  box-sizing: border-box;
  padding-bottom: 10vh;

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 60vh;
  }

  .follow-list {
    display: flex;
    flex-direction: column;

    .follow-item {
      display: flex;
      align-items: center;
      padding: 1vh 0;
      border-bottom: 1px solid #f5f5f5;
      border-radius: 8px;

      &:last-child {
        border-bottom: none;
      }

      &:active {
        background-color: #f9f9f9;
      }

      .avatar-wrapper {
        width: 50px;
        height: 50px;
        flex-shrink: 0;
        margin-right: 3vw;

        .avatar {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
          background-color: #f5f5f5;
        }
      }

      .author-info {
        flex: 1;
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 4px;

        .author-name {
          font-size: 14px;
          color: #333;
          font-weight: 500;
        }

        .author-description {
          font-size: 12px;
          color: #999;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .follow-btn {
        flex-shrink: 0;
        padding: 8px 20px;
        border-radius: 20px;
        background-color: #e5e5e5;
        color: #333;
        font-size: 13px;
        text-align: center;
        cursor: pointer;
        transition: background-color 0.2s, color 0.2s;
        user-select: none;

        &.unfollowed {
          background-color: #ff4757;
          color: #fff;
        }

        &:active {
          opacity: 0.7;
        }
      }
    }
  }
}
</style>
